package org.glut.AppStoreProject.controller;

import com.google.gson.Gson;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import org.glut.AppStoreProject.entity.Users;
import org.glut.AppStoreProject.mapper.UsersMapper;
import org.glut.AppStoreProject.utils.MybatisUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/user/*")
public class UserServlet extends HttpServlet {

    @Override
    protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setHeader("Access-Control-Allow-Methods", "POST, OPTIONS");
        resp.setHeader("Access-Control-Allow-Headers", "Content-Type");
        resp.setStatus(HttpServletResponse.SC_OK);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setHeader("Access-Control-Allow-Origin", "*");
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        Gson gson = new Gson();

        try {
            BufferedReader reader = req.getReader();
            StringBuilder body = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) body.append(line);
            String json = body.toString();
            Users user = gson.fromJson(json, Users.class);

            // 请求类型：登录 / 注册
            String uri = req.getRequestURI();
            if (uri.endsWith("/login")) {
                try (var session = MybatisUtil.getSession()) {
                    UsersMapper mapper = session.getMapper(UsersMapper.class);
                    List<Users> userList = mapper.login(user);
                    if (!userList.isEmpty()) {
                        out.write(gson.toJson(new Result(200, "登录成功", userList.get(0))));
                    } else {
                        out.write(gson.toJson(new Result(401, "用户名或密码错误", null)));
                    }
                }
            } else if (uri.endsWith("/register")) {
                // 注册逻辑：先校验，再插入
                try (var session = MybatisUtil.getSession()) {
                    UsersMapper mapper = session.getMapper(UsersMapper.class);

                    // 校验用户名是否已存在
                    List<Users> existUser = mapper.findByUsername(user.getUsername());
                    if (!existUser.isEmpty()) {
                        out.write(gson.toJson(new Result(400, "用户名已存在", null)));
                        return;
                    }

                    // 插入新用户
                    int rows = mapper.insertUser(user);
                    session.commit();
                    if (rows > 0) {
                        out.write(gson.toJson(new Result(200, "注册成功", user)));
                    } else {
                        out.write(gson.toJson(new Result(500, "注册失败", null)));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.write(gson.toJson(new Result(500, "服务器错误", null)));
        }

    }

    static class Result {
        private int code;
        private String message;
        private Object data;

        public Result(int code, String message, Object data) {
            this.code = code;
            this.message = message;
            this.data = data;
        }
    }
}